
import { defineComponent, defineAsyncComponent, resolveComponent, toRaw, nextTick } from 'vue';
import SceneManager from '../../core/ub/SceneManager.mjs';
/**
 * 生成位图字体
 *
 * @param text 要生成的文本
 * @param width 画布的宽度
 * @param height 画布的高度
 * @returns 返回一个一维数组，表示生成的位图数据
 */
function generateBitmapFont(text, width, height) {
    // 创建一个新的canvas元素  
    const canvas = document.createElement('canvas');
    canvas.width = width;
    canvas.height = height;
    const ctx = canvas.getContext('2d');

    // 设置背景色为白色  
    ctx.fillStyle = 'white';
    ctx.fillRect(0, 0, width, height);

    // 设置文字样式和颜色  
    ctx.font = '10px Arial';
    ctx.fillStyle = 'black';

    // 在canvas上绘制文字  
    ctx.fillText(text, 0, height / 2);

    // 将canvas转换为图片数据  
    const imageData = ctx.getImageData(0, 0, width, height);
    const data = imageData.data;

    // 创建一个二维数组来存储像素值（0表示白色，1表示黑色）  
    const bitmap = Array.from({ length: width }, () => Array(height).fill(0));

    // 遍历每个像素，如果像素是黑色，则将对应位置的数组元素设置为1  
    for (let i = 0; i < data.length; i += 4) {
        if (data[i] > 0) { // R值大于0表示像素为黑色  
            bitmap[i / 4][i / 4 % height] = 1; // i/4是因为一个像素由4个字节（R, G, B, A）组成，i/4 % height是因为我们希望得到的数组与原始canvas尺寸相同  
        }
    }

    // 将二维数组转换为1维数组  
    const flatBitmap = bitmap.flat();

    return flatBitmap; // 返回1维数组形式的点阵数据  
}

let BitmapFonts = defineAsyncComponent(async () => {
    return {
        template: (await axios('./components/bitmapFonts/bitmapFonts.html')).data,
        components: {},
        data() {
            return {
                currentFont: null,
                avaliableFonts: [
                    'serif', 'monospace', 'sans-serif', 'cursive', 'fantasy', 'script',
                    '等线', '黑体', '宋体', '楷体', '仿宋', '隶书', '幼圆', '华文细黑', '微软雅黑'],
                customFonts: [],
                customChatStr: '',
                colors: [{ r: 0, g: 0, b: 0 }, { r: 255, g: 255, b: 255 }],
                displayChar: '',
                scene: null,
                options: null,
                enabled: false,
            }
        },
        watch: {
            customChatStr(v) {
                if (this.currentFont) {
                    this.currentFont.customChars = [...new Set(v.split(''))].sort();
                }
            },
            async scene(scene) {
                // closemsg = OB_IDE.$Message.loading({
                //     content: OB_IDE.$t('正在编译'),
                //     duration: 0
                // });
                // let buf = await OpenBlock.exportExePackage(toRaw(scene));
                // console.log('编译完成');
                // let srcs = OpenBlock.BlocklyParser.loadedFiles.srcs;
                // srcs = srcs.filter(s => scene.srcList.indexOf(s.name) >= 0);
                // let requiredString = srcs.map(s => Object.keys(s.__compiled.relocation.string).reduce((a, b) => a + b).split('')).flat();
                // this.requiredChat = [...new Set(requiredString.flat())].sort();
                // if (this.requiredChat.length > 0) {
                //     this.displayChar = this.requiredChat[0];
                // }
                if (!scene.config.bitmapFonts) {
                    scene.config.bitmapFonts = {};
                }
                if ((!scene.config.bitmapFonts.fonts) || (scene.config.bitmapFonts.fonts.length == 0)) {
                    scene.config.bitmapFonts.fonts = [BitmapFonts.defaultFont()];
                }
                this.customFonts = scene.config.bitmapFonts.fonts;
                this.currentFont = this.customFonts[0];
                this.customChatStr = this.currentFont.customChars.join('');
            },
            displayChar() {
                this.redraw();
            },
            'currentFont.font'() {
                this.redraw();
            },
            'currentFont.size'() {
                this.redraw();
            },
            'currentFont.luminance'() {
                this.redraw();
            },
            enabled(enabled) {
                if (!enabled) {
                    SceneManager.save();
                    OB_IDE.removeComponent(this);
                }
            }
        },
        methods: {
            redraw() {
                let canvas = this.$refs.bitmapFontsCanvas;
                if (!canvas) {
                    nextTick(this.redraw);
                    return;
                }
                if (this.currentFont) {
                    BitmapFonts.drowOnCanvas(canvas, this.currentFont.size, this.currentFont.font, this.displayChar, this.options.colors || this.colors, this.currentFont.luminance);
                }
            },
            showSelectCustomChar() {
                let selectedText = window.getSelection().toString();
                if (selectedText) {
                    this.displayChar = selectedText[0];
                }
            },
            addFonts() {
                let name = prompt(OB_IDE.$t('请输入字体名称'), 'font');
                if (name) {
                    let o = this.customFonts.find(f => f.name == name);
                    if (!o) {
                        let f = JSON.parse(JSON.stringify(
                            this.currentFont ?
                                toRaw(this.currentFont)
                                : BitmapFonts.defaultFont()));
                        f.name = name;
                        this.customFonts.push(f);
                        this.currentFont = f;
                    } else {
                        this.currentFont = o;
                    }
                }
            },
            removeFont() {
                let p = this.customFonts.findIndex(f => f.name == this.currentFont.name);
                if (p >= 0) {
                    this.customFonts.splice(p, 1);
                    this.currentFont = this.customFonts[0] || BitmapFonts.defaultFont();
                }
            }
        }
    }
});
// 创建一个新的style元素  
var style = document.createElement('style');

// 添加样式内容  
style.innerHTML = `
.OB-bitmapFonts-window .ivu-modal-header{
    display: none;
}
#bitmapFontsCanvas{
    width:50%;
    height:auto;
    image-rendering: pixelated;
    border:1px solid gray;
    float:left;
    margin-right:10px;
}
#OB-bitmapFonts-settings{
    float:left;
    width:calc(50% - 10px);
}
#OB-bitmapFonts-chars{
    float:left;
    width:100%;
    max-height:300px;
    overflow-y:auto;
}
`;

// 将style元素添加到head中  
document.head.appendChild(style);
BitmapFonts.openSettings = async function (scene, options) {
    await OpenBlock.saveAllSrc();
    let win = await OB_IDE.addComponent(BitmapFonts);
    win.scene = scene;
    win.options = options;
    win.enabled = true;
};
function groupArray(arr, size) {
    var result = [];
    for (var i = 0; i < arr.length; i += size) {
        result.push(arr.slice(i, i + size));
    }
    return result;
}
BitmapFonts.defaultFont = function () {
    return {
        size: 15, font: 'serif', luminance: 240,
        customChars: [],
    };
}
BitmapFonts.drowOnCanvas = function (canvas, size, font, displayChar, colors, luminance) {
    if (!colors) {
        colors = [{ r: 0, g: 0, b: 0 }, { r: 0, g: 0, b: 255 }]
    }
    let ctx = canvas.getContext('2d');
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.textBaseline = 'top';
    ctx.font = (size) + 'px  ' + font;
    ctx.fillText(displayChar, 1, size / 10, size);

    const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
    const data = imageData.data;
    let points = groupArray(data, 4).map(g => g.reduce((t, v) => t + v, 0));
    points.forEach((v, i, points) => {
        let color;
        if (v < 255 - luminance) {
            color = colors[0];
        } else {
            color = colors[1];
        }
        let style = '#' + color.r.toString(16).padStart(2, '0') + color.g.toString(16).padStart(2, '0') + color.b.toString(16).padStart(2, '0');
        ctx.fillStyle = style;
        ctx.fillRect(i % canvas.width, Math.floor(i / canvas.width), 1, 1);
    });
};
BitmapFonts.charToBytes = function (c, font) {
    return { array: '{0x7,0x8,0x9}', count: 3 };
};
BitmapFonts.toC = function (scene) {
    let srcs = OpenBlock.BlocklyParser.loadedFiles.srcs;
    srcs = srcs.filter(s => scene.srcList.indexOf(s.name) >= 0);
    let requiredString = srcs.map(s => Object.keys(s.__compiled.relocation.string).reduce((a, b) => a + b).split('')).flat();
    let requiredChat = [...new Set(requiredString.flat())];
    let fonts = scene.config.bitmapFonts?.fonts;
    if (!fonts) {
        fonts = [BitmapFonts.defaultFont()];
    }
    let cChars = [];
    fonts.forEach((font, i) => {
        let allChars = requiredChat.concat(font.customChars);
        allChars.sort();
        cChars = cChars.concat(allChars.map((c, i1) => {
            let b = BitmapFonts.charToBytes(c, font);
            return `void bitmapFont_draw_${i}_${i1}(int x,int y){ printf("bitmapFont_draw_${i}_${i1},%d,%d\\n",x,y);}`;
        }));
    });
    let c = cChars.join('\n');
    c = c + "\n#define bitmapFont_draw(font, index, x,y) bitmapFont_draw_##font_##index(x,y)"
    return c;
};
// ${[...new Set(fonts.map((f, i) => { return `uint8_t bitmapFont${i}[${"3" || Math.ceil(f.size * f.size / 8)}];`; }))].join('\n')}
export default BitmapFonts;
BitmapFonts.install = function () {
    class BitmapFontProvier extends OB_NativeBlockArgumentProvider {
        /**
         * 下拉列表的选项
         * @type {Array.<Object.<string,String>>|Function} 国际化->返回值的键值对
         */
        options;
        /**
         * @type {String}
         */
        arg;
        /**
         * @type {String}
         */
        parentBlockType;
        workspace;
        /**
         * 
         * @param {xmldom} blockDom 本地块xml配置中的block节点
         * @param {xmldom} providerCfg 本地块配置中的provider配置
         */
        init(fieldName, blockDom, providerCfg) {
            this.arg = fieldName;
            this.parentBlockType = blockDom.getAttribute('nativeCall');
            this.options = this._options.bind(this);
        }
        /**
         * 
         * @param {Blockly.Workspace} workspace
         * @param {String} checkType 需要的类型
         * @param {String} inputName input名称
         * @param {Blockly.Input} input input对象
         */
        makeBlock(workspace, checkType, inputName, input) {
            if (checkType && checkType !== 'Integer') {
                throw Error('BitmapFontProvier 只支持Integer类型');
            }
            this.workspace = workspace;
            let blk = workspace.newBlock('empty_provider');
            blk.mutation = JSON.stringify({ parentType: this.parentBlockType, argName: this.arg, checkType });
            blk.updateBlock();
            return blk;
        }
        _options() {
            debugger
            let ret = [];
            if (VFS.partition.assets) {
                VFS.partition.assets.allFiles((arr) => {
                    arr.forEach(f => {
                        if (OpenBlock.Utils.mediaType(f.name) == this.mediaType) {
                            ret.push([f.name, f.name]);
                        }
                    });
                });
            }
            if (ret.length == 0) {
                ret.push(['', '']);
            }
            return ret;
        }
    }
    OpenBlock.registerFieldProvider('BitmapFontProvier', BitmapFontProvier);
};